package com.zp.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zp.mall.product.dao.CategoryBrandRelationDao;
import com.zp.mall.product.entity.CategoryBrandRelationEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zp.common.utils.PageUtils;
import com.zp.common.utils.Query;

import com.zp.mall.product.dao.BrandDao;
import com.zp.mall.product.entity.BrandEntity;
import com.zp.mall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<> ();
        String key = (String) params.get ("key");
        if (!StringUtils.isEmpty (key)){
            queryWrapper.eq ("brand_id", key).or ().like ("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updateBrand(BrandEntity brand) {
        BrandEntity byId = this.getById (brand.getBrandId ()); //修改前查出该品牌  获取品牌名称 看与传入的品牌名称是否一致
        this.updateById (brand);  //修改品牌
        if (!byId.getName ().equals (brand.getName ())){
            //品牌名称修改了
            //修改其它表与之关联的品牌名称
            //修改 分类-品牌中间表的品牌名称
            CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity ();
            categoryBrandRelationEntity.setBrandName (brand.getName ());
            categoryBrandRelationEntity.setBrandId (brand.getBrandId ());
            //修改
            categoryBrandRelationDao.update (
                    categoryBrandRelationEntity,
                    new UpdateWrapper<CategoryBrandRelationEntity> ().eq ("brand_id", categoryBrandRelationEntity.getBrandId ())
            );
            //TODO 修改其它表中存的品牌名称
        }
    }

}